import os
import platform
import sys

from funcall.AbstractFunCall import AbstractFunCall, funcallResultMsgBySubprocessResult, fun_call_log_debug, \
    FUN_CALL_REMARK

from conf.config import AppConf, get_environ
from funcall.FuncallInfo import FuncallInfo, funcall_info_to_mysql
from funcalltools.file_utils import fc_write_file
from funcall.funcall_result import FuncallResult
from utils.log_utils import log_title, subprocess_real_time_output


class execute_shell_fun_call(AbstractFunCall):
    def __init__(self):
        self.name = "execute_shell"
        if platform.system() == 'Windows':
            # self.description = "执行windows 脚本,支持javac java mvn python3"
            self.description = "执行windows 脚本,支持javac java mvn python3"
        else:
            # self.description = "执行linux脚本,支持javac java mvn"
            self.description = "执行linux脚本,ubuntu系统,可以使用任何命令"

        work_dir = AppConf['ai']['work_dir']
        # 因为获取当前时间无需输入参数，因此parameters为空字典
        self.parameters = {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": f"要执行的命令, {work_dir},执行后将返回执行结果",
                },
                "remark": {
                    "type": "string",
                    "description": FUN_CALL_REMARK
                }
            }
        }
        self.required = [
            "remark",
            "command"
        ]

    def action(self, jsonRoot):
        command_tmp = jsonRoot['command']
        # self.debug(f"工具调用 execute_shell, \n{log_title('command')}\n{command_tmp}")

        work_dir = AppConf['ai']['work_dir']

        # 使用 os.popen 执行shell
        # os.chdir(work_dir) # 切换到指定目录
        # with os.popen(command_tmp) as f:
        #     output = f.read()

        # # 使用 subprocess 执行shell 不支持单行shell
        import subprocess
        _env = get_environ()  # 复制当前环境变量
        # # 使用 subprocess 执行shell 不支持单行shell
        # import subprocess
        # # 使用subprocess.run并指定cwd参数为工作目录
        funcallInfo=FuncallInfo(description="execute_shell", req_args=command_tmp,status='2');
        funcallInfo.remark=jsonRoot['remark']
        funcall_info_to_mysql(funcallInfo)

        try:
            # _result = subprocess.run([command_tmp],env=_env,cwd=work_dir, capture_output=True, text=True)
            # output=funcallResultMsgBySubprocessResult(_result)

            _result = subprocess.Popen(command_tmp, env=_env, cwd=work_dir, shell=True, stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT, text=True)
            # output = _result.stdout.read()

            output=subprocess_real_time_output(_result.stdout)

            # self.debug(f"工具调用 execute_shell, \n{log_title('command')}\n{command_tmp}\n{log_title('执行结果')}\n{output}")
            funcallInfo.log_text=output
            funcallInfo.status='0'
            fun_call_log_debug(funcallInfo)
        except FileNotFoundError as e:
            # self.debug(f"工具调用 execute_shell, \n{log_title('command')}\n{command_tmp}")
            funcallInfo.status='1'
            funcallInfo.log_text=str(e)
            fun_call_log_debug(funcallInfo)
            raise e

        # self.debug(f"工具调用 execute_shell, command和执行结果=\n{command_tmp}\n{output}")

        return FuncallResult(msg=output).to_json()


if __name__ == '__main__':
    import json
    import logging

    print("setting logging level")
    logging.basicConfig(level=logging.NOTSET)
    logging.debug("asus")
    # 创建一个GetCurrentWeatherFunCall对象
    cw = execute_shell_fun_call()

    # 调用GetCurrentWeatherFunCall对象的call方法
    args = {"command": "ver"}
    args = {"command": "cd"}
    args = {"command": "java Hello.java"}
    args = {"command": "python3 Z:\\aiwork\\app.py"}
    args = {"command": "cd Z:\\aiwork\\erp-service && mvn clean install -l DEBUG"}
    result = cw.call(args)

    # 打印结果
    print(result)
